const tradeService = require('../service/TradeService');
const TradeConverter = require('../converter/TradeConverter');
const AuthUtil = require('../utils/AuthUtil');

// ---------- lambda entry ----------

/**
 * createTrade
 * @param {Object} event
 * @param {Object} context
 * @return {Object}
 */
async function createTrade(event, context) {
  console.info('create trade', event);

  let trade = TradeConverter.createRequestToModel(event.body);

  console.info('converted trade', trade);

  await tradeService.createTrade(trade);

  return {};
}

/**
 * commit
 * @param {Object} event
 * @param {Object} context
 * @return {Object}
 */
async function commit(event, context) {
  console.log('trade commit', event);

  const validUser = AuthUtil.getUsername(event);

  const trades = new Array();
  if (event.body instanceof Array) {
    trades.push(...event.body);
  } else {
    trades.push(event.body);
  }

  const results = new Array([]);
  for (const trade of trades) {
    trades.username = validUser;
    results.push(tradeService.commit(trade));
  }

  await Promise.all(results);

  return {};
}

/**
 * queries
 * @param {Object} event
 * @param {Object} context
 * @return {Array<Trade>}
 */
async function queries(event, context) {
  const where = { status: event.body.status };

  const trades = await tradeService.findAll(where);

  return trades;
}

/**
 * complete
 * @param {Object} event
 * @param {Object} context
 * @return {Object}
 */
async function complete(event, context) {
  const tradeId = event.body.id;

  await tradeService.complete(tradeId);

  return {};
}

/**
 * expire
 * @param {Object} event
 * @param {Object} context
 * @return {Object}
 */
async function expire(event, context) {
  const tradeId = event.body.id;

  await tradeService.expire(tradeId);

  return {};
}

module.exports = {
  createTrade,
  commit,
  queries,
  complete,
  expire,
};

// ---------- internal functions ----------
